package com.guigu.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.community.mapper.CartsMapper;
import com.guigu.community.mapper.ProductMapper;
import com.guigu.community.pojo.Carts;
import com.guigu.community.pojo.Products;
import com.guigu.community.service.CartsService;
import com.guigu.community.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CartsServiceImpl extends ServiceImpl<CartsMapper, Carts> implements CartsService {
    @Autowired
    private CartsMapper cartsMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductService productService;
    @Override
    public boolean addCarts(Integer pid, Integer uid,Integer num) {
        Products products = productMapper.selectById(pid);
        // 根据商品id和用户id查询购物车表中的数据
        //查询条件，根据非主键去查询
        QueryWrapper<Carts> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", pid);//商品id
        wrapper.eq("user_id", uid);//用户id
        Carts cartItem = this.getOne(wrapper);
        if(cartItem == null) {
            // 不存在要添加的购物项，新增
            cartItem = new Carts();
            cartItem.setUserId(uid);
            cartItem.setProductId(pid);
            cartItem.setSum(num);
            cartItem.setSubtotal(products.getSalePrice());
            this.save(cartItem);
        }else {
            // 存在当前要添加的购物项，修改数量和小计
            cartItem.setSum(cartItem.getSum()+1);
            cartItem.setSubtotal(cartItem.getSubtotal() * products.getSalePrice());
            this.updateById(cartItem);
        }
        return true;
    }

    @Override
    public List<Carts> listCarts(Integer uid) {
        return cartsMapper.selectCartsUserId(uid);
    }

    @Override
    public boolean updateCarts(Integer cartId, Integer sum) {
        Carts cart = cartsMapper.selectById(cartId);//根据id查询、
        Products products = this.productService.getById(cart.getProductId());
        // 更新数量
        cart.setSum(sum);
        // 更新小计
        cart.setSubtotal(products.getSalePrice()*cart.getSum());

        return this.updateById(cart);
    }


}
